package com.newtouch.bxzs.enterprise.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.http.HttpUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.newtouch.bxzs.common.base.BaseErrorEnum;
import com.newtouch.bxzs.common.base.BaseException;
import com.newtouch.bxzs.common.base.constant.RabbitMQConstant;
import com.newtouch.bxzs.common.base.em.*;
import com.newtouch.bxzs.common.base.model.Activity;
import com.newtouch.bxzs.common.base.model.PersonalCustomer;
import com.newtouch.bxzs.common.base.model.bo.PushMessageBO;
import com.newtouch.bxzs.common.base.util.*;
import com.newtouch.bxzs.enterprise.mapper.ActivityMapper;
import com.newtouch.bxzs.enterprise.mapper.PersonalCustomerMapper;
import com.newtouch.bxzs.enterprise.model.bo.*;
import com.newtouch.bxzs.enterprise.model.vo.*;
import com.newtouch.bxzs.enterprise.service.ActivityService;
import lombok.SneakyThrows;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.amqp.core.AmqpTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.util.*;

/**
 * 营销活动service实现类
 *
 * <p>
 * <b>History:</b>
 * <table border="1">
 * <tr>
 * <th>Date</th>
 * <th>Operator</th>
 * <th>Memo</th>
 * </tr>
 * <tr>
 * <td>2021年2月9日</td>
 * <td>Amour</td>
 * <td>Create</td>
 * </tr>
 * </table>
 * 
 * @author Amour
 * 
 * @version 1.0.0
 * @since 1.0.0
 */
@Service
public class ActivityServiceImpl implements ActivityService {

	/** 静态变量：系统日志 */
	private static final Log logger = LogFactory.getLog(ActivityServiceImpl.class);

	@Autowired
	ActivityMapper activityMapper;
	@Autowired
	PersonalCustomerMapper personalCustomerMapper;
	@Autowired
	AmqpTemplate rabbitTemplate;
	@Autowired
	RedisUtils redisUtils;
	@Autowired
	CooperationCompanyUtils cooperationCompanyUtils;
	@Value("${organization.type}")
	private String organType;

	private boolean checkCustomer(String customerName, String customerName1, String customerCertificateType,
			String customerCertificateType1, String customerCertificateNumber, String customerCertificateNumber1) {
		return customerName.equals(customerName1) && customerCertificateType.equals(customerCertificateType1)
				&& customerCertificateNumber.equals(customerCertificateNumber1);
	}

	/**
	 * 校验参数
	 * 
	 * @param activityDetail
	 * @param buttonType
	 */
	private void checkParam(ActivityDetailVO activityDetail, String buttonType) {
		if (activityDetail == null || StringUtils.isEmpty(activityDetail.getMarketingActivityTheme())
				|| activityDetail.getMarketingActivityStartTime() == null
				|| activityDetail.getMarketingActivityEndTime() == null
				|| StringUtils.isEmpty(activityDetail.getMarketingActivityScope()) || StringUtils.isEmpty(buttonType)) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
	}

	private void checkParam(String str) {
		if (StringUtils.isEmpty(str)) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
	}

	/**
	 * 保存营销活动信息
	 * 
	 * @param userId
	 * @param activityModifyVO
	 * @return
	 */
	private String modifyActivity(String userId, ActivityModifyVO activityModifyVO) {
		Activity activity = new Activity();
		Date now = new Date();
		// 编辑时只需要修改基本信息
		BeanUtil.copyProperties(activityModifyVO.getActivityDetailVO(), activity);
		activity.setUpdateTime(now);
		activity.setUpdateUserId(userId);
		activity.setPublisherFlag(true);
		if (ButtonTypeEnum.PUBLIC_BUTTON.getCode().equals(activityModifyVO.getButtonType())) {
			activity.setMarketingActivityStatus(PublishStatusEnum.PUBLISHED_STATUS.getResultCode());
		} else {
			activity.setMarketingActivityStatus(PublishStatusEnum.UNPUBLISH_STATUS.getResultCode());
		}
		if (StringUtils.isEmpty(activity.getMarketingActivityId())) {
			// 新增时需要set其他一些属性
			activity.setCreateTime(now);
			activity.setCreateUserId(userId);
			// 通过按钮类型判断活动状态
			activity.setMarketingActivityPublishOrganizationName(
					UserDetailUtil.getUserDetail().getUserOrganizationName());
			activityMapper.insert(activity);
		} else {
			activityMapper.updateById(activity);
		}
		// 发布时需要推送至对端
		if (ButtonTypeEnum.PUBLIC_BUTTON.getCode().equals(activityModifyVO.getButtonType())) {
			ActivityDetailBO activityDetail = new ActivityDetailBO();
			BeanUtil.copyProperties(activity, activityDetail);
			activityDetail.setPublisherFlag(false);
			activityDetail.setMarketingActivityPublishOrganizationName(
					UserDetailUtil.getUserDetail().getUserOrganizationName());
			this.pushManyActivity(activityModifyVO, activityDetail);
	/*		if (DistributionTypeEnum.BANK.getCode().equals(organType)) {
			} else {
				this.pushSingleActivity(activityModifyVO, activityDetail);
			}*/
		}
		return activity.getMarketingActivityId();
	}

	/**
	 * 单次推送营销活动
	 * 
	 * @param activityModifyVO
	 * @param activityDetail
	 */
	private void pushSingleActivity(ActivityModifyVO activityModifyVO, ActivityDetailBO activityDetail) {
		ActivityAcceptionVO activityAcception = new ActivityAcceptionVO();
		SendHttpRequestUtils<ActivityAcceptionVO> sendHttpRequestUtils = new SendHttpRequestUtils<>();
		List<String> productCodeList = new ArrayList<>();
		for (ProductVO product : activityModifyVO.getProductList()) {
			productCodeList.add(product.getProductCode());
		}
		List<String> cooperationUserJobNumberList = new ArrayList<>();
		for (CooperationUserVO cooperationUser : activityModifyVO.getCooperationUserList()) {
			cooperationUserJobNumberList.add(cooperationUser.getCooperationUserJobNumber());
		}
		//添加本端用户与营销会议关联至对端
		List<String> userJobNumberList = new ArrayList<>();
		for (String userJobNumber : activityModifyVO.getUserIdList()) {
			userJobNumberList.add(userJobNumber);
		}
		activityAcception.setActivityDetail(activityDetail);
		activityAcception.setProductCodes(productCodeList);
		activityAcception.setCooperationUserJobNumberList(cooperationUserJobNumberList);
		sendHttpRequestUtils.sendHttpRequest(activityAcception,
				redisUtils.get(CompanyParameterTypeEnum.ACTIVITY_PUSH.getCode()));
	}

	/**
	 * 多次推送营销活动
	 * 
	 * @param activityModifyVO
	 * @param activityDetail
	 */
	private void pushManyActivity(ActivityModifyVO activityModifyVO, ActivityDetailBO activityDetail) {
		Map<String, ActivityAcceptionVO> pushMap = new HashMap<>();
		SendHttpRequestUtils<ActivityAcceptionVO> sendHttpRequestUtils = new SendHttpRequestUtils<>();
		for (ProductVO product : activityModifyVO.getProductList()) {
			ActivityAcceptionVO activityAcceptionVO = pushMap.get(product.getDataSource());
			List<String> productCodes;
			if (activityAcceptionVO == null) {
				activityAcceptionVO = new ActivityAcceptionVO();
				productCodes = new ArrayList<>();
				activityAcceptionVO.setActivityDetail(activityDetail);
				pushMap.put(product.getDataSource(), activityAcceptionVO);
			} else {
				productCodes = activityAcceptionVO.getProductCodes();
			}
			productCodes.add(product.getProductCode());
			activityAcceptionVO.setProductCodes(productCodes);
		}
		for (CooperationUserVO cooperationUser : activityModifyVO.getCooperationUserList()) {
			ActivityAcceptionVO activityAcceptionVO = pushMap.get(cooperationUser.getDataSource());
			List<String> cooperationUserJobNumberList = new ArrayList<>();
			//添加本端用户与营销会议关联至对端
			List<String> userJobNumbers = new ArrayList<>();
			for (String userJobNumber : activityModifyVO.getUserIdList()) {
				userJobNumbers.add(userJobNumber);
			}
			activityAcceptionVO.setUserJobNumberList(userJobNumbers);
			if (activityAcceptionVO == null) {
				activityAcceptionVO = new ActivityAcceptionVO();
				activityAcceptionVO.setActivityDetail(activityDetail);
				pushMap.put(cooperationUser.getDataSource(), activityAcceptionVO);
			} else if (CollectionUtil.isNotEmpty(activityAcceptionVO.getCooperationUserJobNumberList())) {
				cooperationUserJobNumberList = activityAcceptionVO.getCooperationUserJobNumberList();
			}
			cooperationUserJobNumberList.add(cooperationUser.getCooperationUserJobNumber());
			activityAcceptionVO.setCooperationUserJobNumberList(cooperationUserJobNumberList);
		}
		for (Map.Entry<String, ActivityAcceptionVO> entry : pushMap.entrySet()) {
			sendHttpRequestUtils.sendHttpRequest(entry.getValue(), cooperationCompanyUtils.getCompanyUrl(entry.getKey(),
					CompanyParameterTypeEnum.ACTIVITY_PUSH.getCode()));
		}
	}

	/**
	 * 保存营销活动客户信息
	 * 
	 * @param activityId
	 * @param userId
	 * @param customers
	 */
	// private void modifyCustomer(String activityId, String userId,
	// List<CustomerDetailVO> customers) {
	// activityMapper.deleteActivityCustomer(activityId);
	// activityMapper.insertActivityCustomer(activityId, userId, customers);
	// }

	/**
	 * 保存营销活动产品信息
	 * 
	 * @param activityId
	 * @param userId
	 * @param productIdList
	 */
	private void modifyProduct(String activityId, String userId, List<String> productIdList) {
		// 先删除关联表中的现有数据然后重新insert
		activityMapper.deleteActivityProduct(activityId);
		activityMapper.insertActivityProduct(activityId, userId, productIdList);
	}

	/**
	 * 保存合作公司员工信息
	 * 
	 * @param activityId
	 * @param userId
	 * @param cooperationUserIdList
	 */
	private void modifyActivityCooperationUser(String activityId, String userId, List<String> cooperationUserIdList) {
		// 先删除关联表中的现有数据然后重新insert
		activityMapper.deleteActivityCooperationUser(activityId);
		activityMapper.insertActivityCooperationUser(activityId, userId, cooperationUserIdList);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.newtouch.bxzs.enterprise.service.ActivityService#getActivityList(
	 * com.newtouch.bxzs.enterprise.model.ActivityVO)
	 */
	@SneakyThrows
	@Override
	public IPage<ActivityBO> getActivityList(ActivityVO activityVO) {
		if (activityVO.getManagerFlag() == null) {
			logger.error("参数是否为管理岗标识为空!");
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		if (activityVO.getStoryFlag() == null) {
			logger.error("参数是否查询历史活动标识为空!");
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		Page<ActivityBO> page = new Page<>(activityVO.getCurrentPage(), activityVO.getPageSize());
		String userId = UserDetailUtil.getUserDetail().getUserId();
		// 是否查询历史活动
		if (activityVO.getStoryFlag()) {
			return activityMapper.getActivityStoryList(page, userId);
		}
		// 是否为管理岗,管理岗查询自己创建的,其他用户查询自己参与的
		if (activityVO.getManagerFlag()) {
			return activityMapper.getManagerActivityList(page, userId,
					activityVO.getMarketingActivityStartDate() == null ? null
							: DateUtil.formatDateTime(activityVO.getMarketingActivityStartDate()),
					activityVO.getMarketingActivityEndDate() == null ? null
							: DateUtil.formatDateTime(activityVO.getMarketingActivityEndDate()),
					activityVO.getMarketingActivityStatus(), activityVO.getMarketingActivityTheme());
		} else {
			return activityMapper.getActivityList(page, userId,
					activityVO.getMarketingActivityStartDate() == null ? null
							: DateUtil.formatDateTime(activityVO.getMarketingActivityStartDate()),
					activityVO.getMarketingActivityEndDate() == null ? null
							: DateUtil.formatDateTime(activityVO.getMarketingActivityEndDate()),
					activityVO.getMarketingActivityStatus(), activityVO.getMarketingActivityTheme());
		}
	}

	@Override
	public IPage<ActivityBO> getAchievementActivityList(ActivityAchievementVO activityVO) {
		Page<ActivityBO> page = new Page<>(activityVO.getCurrentPage(), activityVO.getPageSize());
		String userId = UserDetailUtil.getUserDetail().getUserId();
		return activityMapper.getAchievementActivityList(page, userId,
				activityVO.getMarketingActivityStartDate() == null ? null
						: DateUtil.format(activityVO.getMarketingActivityStartDate(), "YYYY-MM"),
				activityVO.getMarketingActivityEndDate() == null ? null
						: DateUtil.format(activityVO.getMarketingActivityEndDate(), "YYYY-MM"),
				activityVO.getMarketingActivityTheme(), activityVO.getDataSource());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ActivityService#
	 * getActivityDetail(java.lang.String)
	 */
	@Override
	public ActivityDetailBO getActivityDetail(String activityId, Boolean managerFlag) {
		this.checkParam(activityId);
		return activityMapper.getActivityDetail(managerFlag ? null : UserDetailUtil.getUserDetail().getUserId(),
				activityId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ActivityService#
	 * getActivityCustomerList(java.lang.String, java.lang.String)
	 */
	@Override
	public IPage<ConferenceActivityCustomerBO> getActivityCustomerList(ActivityCustomerVO activityCustomerVO) {
		if (activityCustomerVO.getPublisherFlag() == null || activityCustomerVO.getManagerFlag() == null
				|| StringUtils.isEmpty(activityCustomerVO.getActivityId())) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		Page<ConferenceActivityCustomerBO> page = new Page<ConferenceActivityCustomerBO>(
				activityCustomerVO.getCurrentPage(), activityCustomerVO.getPageSize());
		IPage<ConferenceActivityCustomerBO> result;
		String userId = null;
		if (!activityCustomerVO.getManagerFlag()) {
			userId = UserDetailUtil.getUserDetail().getUserId();
		}
		if (activityCustomerVO.getPublisherFlag()) {
			// 发布方查询推送记录表
			result = activityMapper.getPublisherActivityCustomerList(page, userId, activityCustomerVO.getActivityId(),
					activityCustomerVO.getCustomerName());
		} else {
			// 接收方查询接收记录表
			result = activityMapper.getAcceptionActivityCustomerList(page, userId, activityCustomerVO.getActivityId(),
					activityCustomerVO.getCustomerName());
		}
		if (result == null || CollectionUtil.isEmpty(result.getRecords())) {
			return null;
		}
		// 分页控件会使日期格式注解失效，需重新set数据
		List<ConferenceActivityCustomerBO> bos = new ArrayList<>();
		for (ConferenceActivityCustomerBO bo : result.getRecords()) {
			bo.setCustomerCardTypeName(CustomerCardTypeEnum.getNameByCode(bo.getCustomerCertificateType()));
			bos.add(bo);
		}
		result.setRecords(bos);
		return result;

	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ActivityService#
	 * addActivityPersonalCustomer(java.util.List)
	 */
	@Override
	public Integer insertActivityPersonalCustomer(String activityId, Boolean personalFlag,
			List<CustomerDetailVO> list) {
		this.checkParam(activityId);
		if (CollectionUtil.isEmpty(list)) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		// 查询数据库中现有的客户信息，进行去重校验
		List<CustomerInventoryBO> conferenceCustomers = activityMapper.getActivityCustomerList(activityId);
		if (!CollectionUtil.isEmpty(conferenceCustomers)) {
			List<CustomerDetailVO> repeatCustomers = new ArrayList<>();
			for (CustomerDetailVO customer : list) {
				for (CustomerInventoryBO conferenceCustomer : conferenceCustomers) {
					boolean repeat = this.checkCustomer(conferenceCustomer.getCustomerName(),
							customer.getCustomerName(), conferenceCustomer.getCustomerCertificateType(),
							String.valueOf(customer.getCustomerCertificateType()),
							conferenceCustomer.getCustomerCertificateNumber(), customer.getCustomerCertificateNumber());
					// 重复时将数据添加至重复集合中
					if (repeat) {
						repeatCustomers.add(customer);
						break;
					}
				}
			}
			// 重复集合不为空时，需要根据标识符进行异常处理
			if (!CollectionUtil.isEmpty(repeatCustomers)) {
				// 添加个人客户时，出现重复则直接抛出异常
				if (personalFlag) {
					StringBuffer sb = new StringBuffer();
					for (CustomerDetailVO customer : repeatCustomers) {
						sb.append("【" + customer.getCustomerName() + "】、");
					}
					throw new BaseException(BaseErrorEnum.DATA_EXISTS.getResultCode(),
							sb.substring(0, sb.length() - 1) + "在本次营销活动客户清单存在，请重新选择");
				}
				list.removeAll(repeatCustomers);
			}
		}
		return CollectionUtil.isEmpty(list) ? 0
				: activityMapper.insertActivityCustomer(activityId, UserDetailUtil.getUserDetail().getUserId(), list);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ActivityService#
	 * deleteActivityPersonalCustomer(java.lang.String, java.lang.String)
	 */
	@Override
	public Integer deleteActivityPersonalCustomer(String activityId, String customerId) {
		this.checkParam(activityId);
		this.checkParam(customerId);
		return activityMapper.deleteActivityPersonalCustomer(activityId, customerId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ActivityService#modifyActivity(
	 * com.newtouch.bxzs.enterprise.model.vo.ActivityModifyVO)
	 */
	@Override
	public String modifyActivity(ActivityModifyVO activityModifyVO) {
		// 参数校验
		ActivityDetailVO activityDetail = activityModifyVO.getActivityDetailVO();
		this.checkParam(activityDetail, activityModifyVO.getButtonType());
		// 先保存营销活动信息
		String userId = UserDetailUtil.getUserDetail().getUserId();
		String activityId = this.modifyActivity(userId, activityModifyVO);
		// 保存产品信息
		if (!CollectionUtil.isEmpty(activityModifyVO.getProductList())) {
			List<String> productIdList = new ArrayList<>();
			for (ProductVO product : activityModifyVO.getProductList()) {
				productIdList.add(product.getProductId());
			}
			this.modifyProduct(activityId, userId, productIdList);
		}
		// 保存客户信息,先删除关联表中的数据,再批量insert
		// if
		// (!CollectionUtil.isEmpty(activityModifyVO.getActivityCustomerList()))
		// {
		// this.modifyCustomer(activityId, userId,
		// activityModifyVO.getActivityCustomerList());
		// }
		// 更新本端员工与营销活动关联信息
		List<String> deleteUserList = activityModifyVO.getUserIdDeleteList();
		List<String> insertUserList = activityModifyVO.getUserIdInsertList();
		if (!CollectionUtil.isEmpty(deleteUserList)) {
			// 删除客户关联表中的现有数据
			activityMapper.updateActivityCustomerUser(activityId, deleteUserList);
		}
		// 保存营销活动与本端员工关联表信息
		if (!CollectionUtil.isEmpty(insertUserList)) {
			// 先删除用户关联表中的数据
			activityMapper.deleteActivityUser(activityId);
			activityMapper.insertActivityUser(activityId, userId, insertUserList);
		}
		// 保存合作公司员工信息
		if (!CollectionUtil.isEmpty(activityModifyVO.getCooperationUserList())) {
			List<String> cooperationUserIdList = new ArrayList<>();
			for (CooperationUserVO cooperationUser : activityModifyVO.getCooperationUserList()) {
				cooperationUserIdList.add(cooperationUser.getCooperationUserId());
			}
			this.modifyActivityCooperationUser(activityId, userId, cooperationUserIdList);
		}
		// 如果为发布时，需要发送通知消息
		if (ButtonTypeEnum.PUBLIC_BUTTON.getCode().equals(activityModifyVO.getButtonType())) {
			// 发送消息通知
			PushMessageBO message = PushMessageBO.builder().title("营销活动通知")
					.content("您有新的营销活动待参与,主题为:" + activityDetail.getMarketingActivityTheme())
					.noticeJumpId(activityDetail.getMarketingActivityId()).build();
			rabbitTemplate.convertAndSend(RabbitMQConstant.EXCHANGE_STR, RabbitMQConstant.MESSAGE_NOTICE,
					RabbitMQUtils.createUserIdRabbitMap(insertUserList, message,
							BusinessMessageEnum.MARKETING_ACTIVITY_MESSAGE_REMINDER.getResultCode()));
		}
		return BaseErrorEnum.SUCCESS.getResultCode();
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ActivityService#
	 * getDistributionCustomerList(java.lang.String, java.lang.Boolean)
	 */
	@Override
	public IPage<ConferenceActivityCustomerBO> getDistributionCustomerList(String activityId, Boolean distributionFlag,
			Integer currentPage, Integer pageSize) {
		this.checkParam(activityId);
		IPage<ConferenceActivityCustomerBO> page = activityMapper.getDistributionCustomerList(
				new Page<ConferenceActivityCustomerBO>(currentPage == null ? 1 : currentPage,
						pageSize == null ? 10 : pageSize),
				activityId, distributionFlag);
		if (page != null && !CollectionUtil.isEmpty(page.getRecords())) {
			for (ConferenceActivityCustomerBO customer : page.getRecords()) {
				customer.setCustomerCardTypeName(
						CustomerCardTypeEnum.getNameByCode(customer.getCustomerCertificateType()));
			}
		}
		return page;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ActivityService#
	 * modifyDistributionCustomer(java.lang.String, java.lang.String,
	 * java.lang.String)
	 */
	@Override
	public Integer modifyDistributionCustomer(DistributionCustomerVO distributionCustomerVO) {
		this.checkParam(distributionCustomerVO.getConferenceId());
		if (CollectionUtil.isEmpty(distributionCustomerVO.getCustomerList())) {
			throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
		}
		if (StringUtils.isEmpty(distributionCustomerVO.getUserId())){
			//移除分配
			//移除个人客户
			personalCustomerMapper.deleteCustomer(distributionCustomerVO.getCustomerList().get(0).getCustomerId(),true);
			//修改客户id与营销会议关联
			distributionCustomerVO.getCustomerList().get(0).setCustomerId(null);
			return activityMapper.updateDistributionCustomer(distributionCustomerVO.getConferenceId(),
					distributionCustomerVO.getUserId(), distributionCustomerVO.getCustomerList());
		}else {
			if (StringUtils.isEmpty(distributionCustomerVO.getUserJobNumber())) {
				throw new BaseException(BaseErrorEnum.REQUEST_DATA_NULL);
			}
			for (int i = 0; i < distributionCustomerVO.getCustomerList().size(); i++) {
				if (StringUtils.isEmpty(distributionCustomerVO.getCustomerList().get(i).getCustomerId())) {
					QueryWrapper<PersonalCustomer> query = new QueryWrapper<>();
					query.eq("CUSTOMER_NAME", distributionCustomerVO.getCustomerList().get(i).getCustomerName());
					query.eq("CUSTOMER_CERTIFICATE_TYPE", distributionCustomerVO.getCustomerList().get(i).getCustomerCertificateType());
					query.eq("CUSTOMER_CERTIFICATE_NUMBER", distributionCustomerVO.getCustomerList().get(i).getCustomerCertificateNumber());
					query.eq("USER_JOB_NUMBER", distributionCustomerVO.getUserJobNumber());
					PersonalCustomer personalCustomer = personalCustomerMapper.selectOne(query);
					if (personalCustomer == null) {
						personalCustomer = new PersonalCustomer();
						// 写入个人客户表
						BeanUtil.copyProperties(distributionCustomerVO.getCustomerList().get(i), personalCustomer);
						// 姓名全拼
						personalCustomer.setCustomerNameFullSpelling(PinYinUtils.toPinyin(personalCustomer.getCustomerName()));
						// 标识
						personalCustomer.setCustomerLabel(CustomerTagEnum.LSSUED.getCode());
						// 所属用户工号
						personalCustomer.setUserJobNumber(distributionCustomerVO.getUserJobNumber());
						personalCustomer.setCreateTime(new Date());
						personalCustomer.setCreateUserId(UserDetailUtil.getUserDetail().getUserId());
						personalCustomerMapper.insert(personalCustomer);
					}
					distributionCustomerVO.getCustomerList().get(i).setCustomerId(personalCustomer.getCustomerId());
				}
			}
		}
		return activityMapper.updateDistributionCustomer(distributionCustomerVO.getConferenceId(),
				distributionCustomerVO.getUserId(), distributionCustomerVO.getCustomerList());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ActivityService#cancelActivity(
	 * java.lang.String)
	 */
	@Override
	public Integer cancelActivity(String activityId) {
		this.checkParam(activityId);
		return activityMapper.updateActivityStatus(activityId, PublishStatusEnum.CANCELED_STATUS.getResultCode());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ActivityService#deleteActivity(
	 * java.lang.String)
	 */
	@Override
	public Integer deleteActivity(String activityId) {
		this.checkParam(activityId);
		return activityMapper.deleteById(activityId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ActivityService#
	 * getActivityStatistics(java.lang.String)
	 */
	@Override
	public ConferenceActivityStatisticsBO getActivityStatistics(String activityId) {
		this.checkParam(activityId);
		ConferenceActivityStatisticsBO result = activityMapper.getActivityStatistics(activityId);
		List<String> unifiedSocialCreditCode = activityMapper.getUnifiedSocialCreditCodeByActivity(activityId);
		unifiedSocialCreditCode.stream().forEach(e ->{
			String url = cooperationCompanyUtils.getCompanyUrl(e,CompanyParameterTypeEnum.MARKET_RECOMMENDATION.getCode());
			Map repMap = new HashMap(1);
			repMap.put("relationId",activityId);
			String count = HttpUtil.get(url, repMap);
			result.setRecommendationNum(result.getRecommendationNum()+Integer.valueOf(count));
		});
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ActivityService#
	 * acceptionActivity(com.newtouch.bxzs.enterprise.model.bo.
	 * ActivityDetailBO)
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public Integer acceptionActivity(ActivityAcceptionVO activityAcception) {
		Activity activity = new Activity();
		BeanUtil.copyProperties(activityAcception.getActivityDetail(), activity);
		activity.setPublisherFlag(false);
		Integer result = activityMapper.insertActivity(activity);
		if (!CollectionUtil.isEmpty(activityAcception.getProductCodes())) {
			// 产品与营销会议关联信息入库
			List<String> productList = activityMapper.getProductIdByCode(activityAcception.getProductCodes());
			activityMapper.insertActivityProduct(activity.getMarketingActivityId(), "admin", productList);
		}
		if (!CollectionUtil.isEmpty(activityAcception.getCooperationUserJobNumberList())) {
			// 用户与营销活动关联信息入库
			activityMapper.insertActivityUserByJobNumber(activity.getMarketingActivityId(),
					activityAcception.getCooperationUserJobNumberList(),false);
			//对端用户与营销会议关联信息入库
			activityMapper.insertActivityCooperationUserByJobNumber(activity.getMarketingActivityId(),
					activityAcception.getUserJobNumberList(),true);
			// 发送消息通知
			PushMessageBO message = PushMessageBO.builder().title("营销活动通知")
					.content("您有新的营销活动待参与,主题为:" + activity.getMarketingActivityTheme())
					.noticeJumpId(activity.getMarketingActivityId()).build();
			rabbitTemplate.convertAndSend(RabbitMQConstant.EXCHANGE_STR, RabbitMQConstant.MESSAGE_NOTICE,
					RabbitMQUtils.createUserJobNumberRabbitMap(activityAcception.getCooperationUserJobNumberList(),
							message, BusinessMessageEnum.MARKETING_ACTIVITY_MESSAGE_REMINDER.getResultCode()));
		}
		return result;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ActivityService#
	 * getActivityProduct(com.newtouch.bxzs.enterprise.model.vo.
	 * ActivityProductVO)
	 */
	@Override
	public IPage<ConferenceActivityProductBO> getActivityProduct(ActivityProductVO activityProductVO) {
		return activityMapper.getActivityProduct(
				new Page<ConferenceActivityProductBO>(activityProductVO.getCurrentPage(),
						activityProductVO.getPageSize()),
				activityProductVO.getActivityId(), activityProductVO.getProductName());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.newtouch.bxzs.enterprise.service.ActivityService#getActivityUser(
	 * com.newtouch.bxzs.enterprise.model.vo.ActivityUserVO)
	 */
	@Override
	public IPage<ConferenceActivityUserBO> getActivityUser(ActivityUserVO activityUserVO) {
		return activityMapper.getActivityUser(
				new Page<ConferenceActivityUserBO>(activityUserVO.getCurrentPage(), activityUserVO.getPageSize()),
				activityUserVO.getActivityId(), activityUserVO.getSelectCondition());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ActivityService#
	 * getActivityCooperationUser(com.newtouch.bxzs.enterprise.model.vo.
	 * ActivityUserVO)
	 */
	@Override
	public IPage<ConferenceActivityUserBO> getActivityCooperationUser(ActivityUserVO activityUserVO) {
		return activityMapper.getActivityCooperationUser(
				new Page<ConferenceActivityUserBO>(activityUserVO.getCurrentPage(), activityUserVO.getPageSize()),
				activityUserVO.getActivityId(), activityUserVO.getSelectCondition());
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see com.newtouch.bxzs.enterprise.service.ActivityService#joinActivity(
	 * java.lang.String)
	 */
	@Override
	public Integer joinActivity(String userId, String activityId) {
		return activityMapper.joinActivity(userId, activityId);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.newtouch.bxzs.enterprise.service.ActivityService#contactCustomer(java
	 * .lang.String, com.newtouch.bxzs.enterprise.model.vo.CustomerDetailVO)
	 */
	@Override
	public Integer contactCustomer(String activityId, CustomerDetailVO customer) {
		return activityMapper.contactCustomer(activityId, customer);
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see
	 * com.newtouch.bxzs.enterprise.service.ActivityService#pushCustomer(java.
	 * lang.String, com.newtouch.bxzs.enterprise.model.vo.CustomerDetailVO)
	 */
	@Override
	@Transactional(rollbackFor = Exception.class)
	public String pushCustomer(String activityId, CustomerDetailVO customer) {
		/*
		 * 若个人客户表中不存在该客户数据,则将客户数据写入个人客户表,否则更新客户与营销会议关联表中的ID
		 */
		// 不存在客户ID时才进行入库操作
		if (StringUtils.isEmpty(customer.getCustomerId())) {
			String userJobNumber = UserDetailUtil.getUserDetail().getUserJobNumber();
			QueryWrapper<PersonalCustomer> query = new QueryWrapper<>();
			query.eq("CUSTOMER_NAME", customer.getCustomerName());
			query.eq("CUSTOMER_CERTIFICATE_TYPE", customer.getCustomerCertificateType());
			query.eq("CUSTOMER_CERTIFICATE_NUMBER", customer.getCustomerCertificateNumber());
			query.eq("USER_JOB_NUMBER", userJobNumber);
			PersonalCustomer personalCustomer = personalCustomerMapper.selectOne(query);
			if (personalCustomer == null) {
				personalCustomer = new PersonalCustomer();
				// 写入个人客户表
				BeanUtil.copyProperties(customer, personalCustomer);
				// 姓名全拼
				personalCustomer.setCustomerNameFullSpelling(PinYinUtils.toPinyin(personalCustomer.getCustomerName()));
				// 标识
				personalCustomer.setCustomerLabel(CustomerTagEnum.LSSUED.getCode());
				// 所属用户工号
				personalCustomer.setUserJobNumber(userJobNumber);
				personalCustomer.setCreateTime(new Date());
				personalCustomer.setCreateUserId(UserDetailUtil.getUserDetail().getUserId());
				personalCustomerMapper.insert(personalCustomer);
			}
			// 更新客户与营销会议关联表
			customer.setCustomerId(personalCustomer.getCustomerId());
			activityMapper.updateCustomerId(activityId, customer);
			return personalCustomer.getCustomerId();
		}
		return "";
	}
}
